package cn.chenyumeng.blog.service.admin.impl;

import cn.chenyumeng.blog.dto.UserDTO;
import cn.chenyumeng.blog.mapper.UserMapper;
import cn.chenyumeng.blog.entity.User;
import cn.chenyumeng.blog.service.admin.UserService;
import cn.chenyumeng.blog.util.MD5Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @program: blog->UserServiceImpl
 * @description:
 * @author: cg
 * @create: 2020-07-26 13:54
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Transactional
    @Override
    public UserDTO checkUser(String username, String password) {
        User user = userMapper.queryByUsernameAndPassword(username, password);
        UserDTO dto = new UserDTO();
        BeanUtils.copyProperties(user, dto);
        dto.setToken(MD5Utils.code(dto.getUsername()));
        return dto;
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Transactional
    @Override
    public User queryById(Long id) {
        return this.userMapper.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Transactional
    @Override
    public List<User> queryAllByLimit(int offset, int limit) {
        return this.userMapper.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Transactional
    @Override
    public User insert(User user) {
        this.userMapper.insert(user);
        return user;
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Transactional
    @Override
    public User update(User user) {
        this.userMapper.update(user);
        return this.queryById(user.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Transactional
    @Override
    public boolean deleteById(Long id) {
        return this.userMapper.deleteById(id) > 0;
    }

    /**
     * 通过Token和userId判断是否存在该用户
     *
     * @param token
     * @param userId
     * @return
     */
    @Transactional
    @Override
    public boolean hasUser(String token, Long userId) {
        User user = userMapper.queryById(userId);
        if (user == null) {
            return false;
        }
        if (!token.equals(MD5Utils.code(user.getUsername()))) {
            return false;
        }
        return true;
    }
}
